const validate = require("validate.js");
const blogDao = require("../dao/blogDao");
const blogtypeDao = require("../dao/blogtypeDao");
const Blogtype = require("../dao/models/Blogtype");
const { ValidationError } = require("../utils/errors");
const generateTOC = require("../utils/generateTOC");

validate.validators.categoryExist = async (value) => {
    const res = await Blogtype.findByPk(value);
    if (!res) {
        return "is not exist";
    }
}

exports.addBlog = async (info) => {
    info = generateTOC(info);
    info.scanNumber = 0;
    info.commentNumber = 0;
    info.toc = JSON.stringify(info.toc);
    const rule = {
        title: {
            presence: {
                allowEmpty: false
            },
            type: "string"
        },
        description: {
            presence: {
                allowEmpty: true
            },
            type: "string"
        },
        toc: {
            presence: {
                allowEmpty: true
            },
            type: "string"
        },
        htmlContent: {
            presence: {
                allowEmpty: false
            },
            type: "string"
        },
        thumb: {
            type: "string"
        },
        scanNumber: {
            presence: {
                allowEmpty: false
            },
            type: "integer"
        },
        commentNumber: {
            presence: {
                allowEmpty: false
            },
            type: "integer"
        },
        createDate: {
            presence: {
                allowEmpty: false
            },
            type: "integer"
        },
        categoryId: {
            presence: true,
            type: "integer",
            categoryExist: true
        }
    }

    try {
        await validate.async(info, rule);
        await blogtypeDao.addBlogtypeCount(info.categoryId);
        return await blogDao.addBlog(info);
    } catch (err) {
        throw new ValidationError("数据验证失败");
    }
}

exports.getBlogs = async (page, limit, id) => {
    const res = await blogDao.getBlogs(page, limit, id);
    res.rows = res.rows.map((blog) => {
        return {
            ...blog,
            toc: JSON.parse(blog.toc)
        }
    });
    return res;
}

exports.getBlogById = async (id, token) => {
    const res = await blogDao.getBlogById(id, token);
    res.toc = JSON.parse(res.toc);
    return res;
}

exports.updateBlog = async (id, info) => {
    if (info.hemlContent) {
        info = generateTOC(info);
        info.toc = JSON.stringify(info.toc);
    }
    return await blogDao.updateBlog(id, info);
}

exports.deleteBlog = async (id) => {
    await blogDao.deleteBlog(id);
    return true;
}
